package com.tcs.gather.commod.exec.input.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcs.gather.commod.exec.input.AbstractInputCommod;
import com.tcs.gather.model.CommandModel;
import com.tcs.gather.model.logger.LoggerCommandModel;
import com.tcs.queue.ISingleionQueue;

/**
 * 日志采集命令
 * @Title: InputLoggerCommod.java
 * @Package com.tcs.gather.commod.exec.input.impl
 * @author 神经刀
 * @date 2018年3月21日
 * @version V1.0
 */
public class InputLoggerCommod extends AbstractInputCommod {

	private final Logger logger = LoggerFactory.getLogger(InputLoggerCommod.class);
	
	public InputLoggerCommod() {};
	
	public InputLoggerCommod(CommandModel commandModel,ISingleionQueue<String> queue) {
		super(commandModel,queue);
	}

	@Override
	public void execInputCommod(CommandModel commandModel) {
		LoggerCommandModel loggerCommandModel = (LoggerCommandModel)commandModel;
		Runtime r = Runtime.getRuntime();
		BufferedReader in = null;
		Process process = null;
		String readLine = null;
		String commodStr = loggerCommandModel.getInputCommod() + loggerCommandModel.getInputPath() + loggerCommandModel.getInputFile();
		logger.info(" commodStr : {} ", commodStr);
		try {
			process = r.exec(commodStr);
			try {
				in = new BufferedReader(new InputStreamReader(process.getInputStream())); // 逐行检查输出,计算类似出现=23ms
				while (true) {
					// 如果没有数据,则休眠5秒钟,直到有数据才开始
					if ((readLine = in.readLine()) == null) {
						Thread.sleep(5 * 1000L);
					}
					logger.info("readLine : {} , size : {} ", readLine , this.queue.size());
					if (StringUtils.isNotEmpty(readLine)) {
						this.affer(readLine);
					}
				}
			} catch (Exception e) {
				logger.error("", e);
				try {
					in.close();
				} catch (IOException e1) {
					logger.error("", e1);
				}
			}
		} catch (IOException e) {
			logger.error("", e);
		}
	}
	
}